package com.lottery.im.module.contact.ui;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lottery.im.R;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.ui.NewFragmentActivity;
import com.lottery.im.module.contact.adapter.FriendMrgMsgAdapter;
import com.lottery.im.module.contact.adapter.GroupMrgMsgAdapter;
import com.lottery.im.module.contact.presenter.ShipManageMessagePresenter;
import com.lottery.im.module.contact.view.ShipManageMessageView;
import com.lottery.im.module.tim.model.FriendFuture;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.lottery.im.module.tim.model.GroupFuture;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.ext.group.TIMGroupPendencyItem;
import com.tencent.imsdk.ext.sns.TIMFriendFutureItem;
import java.util.ArrayList;
import java.util.List;

/*
 *  验证通知管理界面 (好友验证 + 入群验证)
 *  偷懒模式：一个tab+两个RecyclerView简单实现
 * */
public class ShipManageMessageFragment extends BaseSwipeFragment<ShipManageMessagePresenter>
    implements ShipManageMessageView {

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.tabLayout) CommonTabLayout mTabLayout;
  @BindView(R.id.list_friend) RecyclerView mListFriend;
  @BindView(R.id.list_group) RecyclerView mListGroup;

  private String[] mTabNames = { "好友验证", "入群验证" };

  private List<FriendFuture> mFriendFutures = new ArrayList<>();
  private FriendMrgMsgAdapter mFriendMrgMsgAdapter;

  private List<GroupFuture> mGroupFutures = new ArrayList<>();
  private GroupMrgMsgAdapter mGroupMrgMsgAdapter;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_shipmanage_message;
  }

  @Override protected void initPresenter() {
    presenter = new ShipManageMessagePresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {

    mTvTitle.setText("验证通知");
    initTabs();

    mListFriend.setLayoutManager(new LinearLayoutManager(mActivity));
    mListGroup.setLayoutManager(new LinearLayoutManager(mActivity));

    mFriendMrgMsgAdapter = new FriendMrgMsgAdapter(mFriendFutures);
    mFriendMrgMsgAdapter.setOnItemChildClickListener(
        (adapter, view, position) -> {

          String id = mFriendFutures.get(position).getIdentify();
          switch (view.getId()) {
            case R.id.btn_agree:
              presenter.setFriendRequest(id, 1);
              break;
            case R.id.btn_refuse:
              presenter.setFriendRequest(id, 2);
              break;
          }
        });
    mFriendMrgMsgAdapter.setOnItemClickListener(
        (adapter, view, position) -> NewFragmentActivity.create(mActivity,
            NewFragmentActivity.FragmentInfoType.Other,
            mFriendFutures.get(position).getIdentify()));
    mListFriend.setAdapter(mFriendMrgMsgAdapter);

    mGroupMrgMsgAdapter = new GroupMrgMsgAdapter(mGroupFutures);
    mGroupMrgMsgAdapter.setOnItemChildClickListener(
        (adapter, view, position) -> {

          TIMGroupPendencyItem futureItem = mGroupFutures.get(position).getFutureItem();
          switch (view.getId()) {
            case R.id.btn_agree:
              presenter.setGroupRequest(futureItem, 1);
              break;
            case R.id.btn_refuse:
              presenter.setGroupRequest(futureItem, 2);
              break;
          }
        });
    mListGroup.setAdapter(mGroupMrgMsgAdapter);

    presenter.initManagerPresenter();
  }

  @OnClick(R.id.iv_back) public void onViewClicked() {
    popBackStack();
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < mTabNames.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          return mTabNames[position];
        }

        @Override public int getTabSelectedIcon() {
          return 0;
        }

        @Override public int getTabUnselectedIcon() {
          return 0;
        }
      });
    }
    mTabLayout.setTabData(tabEntities);
    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        if (position == 0) {
          mListGroup.setVisibility(View.GONE);
          mListFriend.setVisibility(View.VISIBLE);
        } else {
          mListFriend.setVisibility(View.GONE);
          mListGroup.setVisibility(View.VISIBLE);
        }
      }

      @Override public void onTabReselect(int position) {

      }
    });
  }

  /*
   * 刷新好友验证
   * */
  @Override public void refreshFriendAdapter(List<TIMFriendFutureItem> message) {
    mFriendFutures.clear();
    for (TIMFriendFutureItem item : message) {
      mFriendFutures.add(new FriendFuture(item));
    }
    mFriendMrgMsgAdapter.notifyDataSetChanged();
    // 由于api回调没有头像信息 去加载申请人的头像
    List<String> ids = new ArrayList<>();
    for (FriendFuture future : mFriendFutures) {
      if (TextUtils.isEmpty(future.getFaceUrl()) && null == FriendshipInfo.getInstance()
          .getProfile(future.getIdentify())) {
        ids.add(future.getIdentify());
      }
    }
    if (ids.size() == 0) {
      return;
    }
    presenter.getUsersProfile(1, ids);
  }

  /*
   * 刷新群聊验证
   * */
  @Override public void refreshGroupAdapter(List<TIMGroupPendencyItem> message) {
    mGroupFutures.clear();
    for (TIMGroupPendencyItem item : message) {
      mGroupFutures.add(new GroupFuture(item));
    }
    mGroupMrgMsgAdapter.notifyDataSetChanged();

    // 由于api回调没有头像信息 去加载申请人的头像
    List<String> ids = new ArrayList<>();
    for (GroupFuture future : mGroupFutures) {

      if (future.getFromeUserName().equals(future.getFutureItem().getFromUser())) {
        ids.add(future.getFutureItem().getFromUser());
      }
    }
    if (ids.size() == 0) {
      return;
    }
    presenter.getUsersProfile(2, ids);
  }

  /*
   * 好友验证、群验证 获取头像返回
   * type 1 好友验证的时候 2 群验证的时候
   * */
  @Override public void getUsersProfileSuccess(int type, List<TIMUserProfile> timUserProfiles) {
    if (type == 1) {
      for (TIMUserProfile profile : timUserProfiles) {
        for (int i = 0; i < mFriendFutures.size(); i++) {
          if (mFriendFutures.get(i).getIdentify().equals(profile.getIdentifier())) {
            mFriendFutures.get(i).setFaceUrl(profile.getFaceUrl());
            mFriendMrgMsgAdapter.notifyDataSetChanged();
            break;
          }
        }
      }
    } else {

      for (TIMUserProfile profile : timUserProfiles) {
        for (int i = 0; i < mGroupFutures.size(); i++) {
          if (mGroupFutures.get(i).getFutureItem().getFromUser().equals(profile.getIdentifier())) {
            mGroupFutures.get(i).setFromeUserName(profile.getNickName());
            mGroupFutures.get(i).setFromeUserAvatarUrl(profile.getFaceUrl());
            mGroupMrgMsgAdapter.notifyDataSetChanged();
            break;
          }
        }
      }
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    presenter.onDestroy();
  }
}
